<?php
/* 不能改成file，名字与lib/file.php库文件发生冲突 V1.3 */
App::uses('WeixinUtility', 'Utility');
App::uses('CrawlUtility', 'Utility');
class AppUploadfilesController extends AppController {
	var $name = 'AppUploadfiles';
	var $helpers = array (
			'Html' 
	);
	
	var $appUser = array();
	public $app_id = null;
	
	var $components = array(
			'Auth' => array(
					'authenticate' => array(
							'Form'=>array(
									'userModel' => 'User','recursive' => 1,
									'fields'=>array(
											'username'=>'email',
											'password'=>'password'
									)
							),
					),
					'authorize' => array(
						'all' => array(
							'actionPath' => 'controllers/'
						),
						'Crud',
					)
			),
			'Acl',
			'Session',
			'SwfUpload' 
	);
	
	function beforeFilter() {
		// print_r($_POST);print_r($_COOKIE);print_r($_FILES);exit;
		
	    if (isset ( $_POST ['PHPSESSID'] ) && ! empty ( $_POST ['PHPSESSID'] )) {
	        $_POST ['PHP_SESSION_ID'] =  $_POST ['PHPSESSID'];
	    }
	    
		// flash传输过来的，只使用session验证
		if (isset ( $_POST ['PHP_SESSION_ID'] ) && ! empty ( $_POST ['PHP_SESSION_ID'] )) {
			$this->Session->id ( $_POST ['PHP_SESSION_ID'] );
			$_COOKIE ['PHPSESSID'] = $_POST ['PHP_SESSION_ID'];
			$_COOKIE ['MIAOCMS'] ['Auth'] ['User'] = $_POST ['MIAOCMS'] ['Auth'] ['User'];

			$this->Cookie = $this->Components->load('Cookie',array('name' => 'MIAOCMS', 'time' => '+2 weeks'));
    		$user = $this->Cookie->read('Auth.User');
    		/** 直接登录用户 **/
    		if(isset($user['id']) && intval($user['id'])>0){
    			$this->loadModel('User');
    			$data = $this->User->getUserInfo($user['id']);
    			$this->Session->write('Auth.User',$data['User']);
    		}
    		else{
    			$_COOKIE ['MIAOCMS'] ['Auth'] ['User'] = null;
    		}
		}
		
		$this->autoRender = false;
		parent::beforeFilter ();
		
		if( !empty($_REQUEST['little_id'])) {
		    $this->app_id = $_REQUEST['little_id'];
		}
		
		$this->appUser = $this->Session->read('Auth.AppUser');
		
		/*if($this->appUser['id']) {
			$wxinfo = $this->Session->read('User.wxinfo');
			if(empty($wxinfo)) {
				$this->loadModel('User');
				$wxinfo = $this->User->getUserWxes(1);
				if(!empty($wxinfo)){
					$this->Session->write('User.wxinfo',$wxinfo);
				}
			}
			if( !empty($wxinfo) && $wxinfo['Wx']['oauth_appid'] ) {
				WeixinUtility::$appId = $wxinfo['Wx']['oauth_appid'];
			}
		}*/
		
		session_write_close(); // 强制关闭session，释放session锁
		
		$this->Auth->allowedActions = array('ueditor','check','upload','mine','wordToHtml');
	}
	
	public function uploadWechatByUrl(){
	    
	    $imageurl = $_POST['uri'];
	    if($imageurl){
	        $file = CrawlUtility::saveImagesByUrl($imageurl,'',array('oss'=>false,'resize'=>false));
	        if($file && file_exists(UPLOAD_FILE_PATH . $file)) {
	            $file = UPLOAD_FILE_PATH . $file;
	            $ret = WeixinUtility::add_material($file, 'image');
	            @unlink($file);
	            if($ret['media_id']) {
	                $ret['url'] = 'http://image2.135editor.com/cache/remote/'.base64_encode($ret['url']);
	                $ret['success'] = '图片已成功同步至微信';
	                echo json_encode($ret);
	                exit;
	            }
	            else{
	                echo json_encode(array('code'=>-1,'error'=>'上传微信失败'));
	            }
	        }
	        else{
	            echo json_encode(array('code'=>-2,'error'=>'创客贴封面图片获取失败'));
	        }
	    }
	    else{
	        echo json_encode(array('code'=>-3,'error'=>'没有uri参数'));
	    }
	    exit;
	}
	
	public function uploadBase64(){
	    
	    $content = file_get_contents('php://input', 'r');
	    $length = strlen($content);
	    $imgtype=$imgcontent = '';
	    //data:image/png;base64,
        if( 'data:image/' == substr($content,0,11) ) {
            for( $j=11; $j<$length && $content[$j]!=';'; $j++ ) {
                $imgtype .= $content[$j];
            }
            // $j=$j+7 skip "base64,"
            $imgcontent = substr($content,$j+7);
            //CakeLog::debug($imgcontent);
            
            $imgcontent = base64_decode($imgcontent);
            
            if( strlen($imgcontent) > 1024000 * 2 ) {
                echo json_encode(array('ret'=>1,'msg'=>'数据大于2M，禁止上传'));
            }
            else{
                $url = $this->_saveImageContent($imgtype,$imgcontent);
                echo json_encode(array('ret'=>0,'url'=>$url));
            }         
        }
        else{
            echo json_encode(array('ret'=>1,'msg'=>'base64 data error'));
        }
        exit;
	    
	}
	
	public function uploadByUrl(){
	    $imageurl = $_POST['uri'];
	    if($imageurl){
	        $fileurl = CrawlUtility::saveImagesByUrl($imageurl,'',array('oss'=>true,'resize'=>false));	        
	        if( $fileurl ) {
	            
	            $this->data['AppUploadfile'] = array();
	            $this->data['AppUploadfile']['modelclass'] = $_POST['model'] ? $_POST['model'] :  'WxMsg';
	            $this->data['AppUploadfile']['user_id'] = $this->appUser['id'];
	            $this->data['AppUploadfile']['fieldname'] = $_POST['field'] ? $_POST['field'] :  'coverimg';
	            $this->data['AppUploadfile']['fspath'] = $fileurl;
	            	
	            $this->AppUploadfile->save ( $this->data );
	            
	            $ret = array(
	                'url' => $fileurl,
	                'success' => '图片已成功上传',
	            );
                echo json_encode($ret);
                exit;
	        }
	        else{
	            echo json_encode(array('code'=>-2,'error'=>'图片保存失败，请重试'));
	        }
	    }
	    else{
	        echo json_encode(array('code'=>-3,'error'=>'参数错误，没有uri参数'));
	    }
	    exit;
	}
	
	public function download($id){
		
		if(empty($this->appUser['id'])){
			echo json_encode(array('ret' => -1,'error'=> __('You need to login')));exit;
		}
		
		$fileinfo = $this->AppUploadfile->findById($id);
		if(!empty($fileinfo)){
			$filename = $fileinfo['AppUploadfile']['fspath'];
			
			if( strpos($filename, 'http://')!==false || strpos($filename, 'https://')!==false  ) {
			    header('Location:'.$filename);
			}
			else{
			    header("Content-Type: application/force-download");
			    header("Content-Disposition: attachment; filename=".basename($filename));
			    echo file_get_contents(UPLOAD_FILE_PATH.$filename);
			}			
		}
		else{
			throw new NotFoundException(__('Error url,this url page is not exist.'));
		}
	}
	
	public function upload_inline(){
	    
	    if(!empty($_FILES)) {
	        print_r($_FILES);exit;
	    }
	    
	    $this->autoRender = true;
	    
		if (empty($this->appUser['id'])) {
            $this->redirect('/users/login');
        }

		$file_post_name = 'file';
		$file_model_name = 'BookChapter';
		if (isset ( $this->params ['form'] [$file_post_name] )) {
			// upload the file
			$this->SwfUpload->gen_thumb = false;
			$this->SwfUpload->file_post_name = $file_post_name;
			if ($fileinfo = $this->SwfUpload->upload ()) {
				$data['modelclass'] = $file_model_name;
				$data['fieldname'] = $file_post_name;
				$data['name'] = $this->SwfUpload->filename;
				$data['size'] = $this->params ['form'] [$file_post_name] ['size'];
				$data['fspath'] = str_replace ( '\\', '/', $this->SwfUpload->relativeUrl . $this->SwfUpload->savename );

				$data['type'] = $fileinfo['file_type'];
				$file = $this->AppUploadfile->save( $data);
				echo $data['fspath'];
				exit;
			}
		}
	}
	public function delete_inline(){
		$file_post_name = 'file';
		$file_model_name = 'BookChapter';
	}
	
	private function _unlink($file) {
	    if(empty($file)) {
	        return;
	    }
		if(strpos($file,'http') === false) {
			@unlink(UPLOAD_FILE_PATH.$file);
		}
		else{
			
			if( strpos($file,'http://qdn.135editor.com/') !== false) { //七牛云存储
				$object_name = str_replace('http://qdn.135editor.com/','',$file);
				CrawlUtility::delFromQiniu($object_name);
			}
			elseif( strpos($file,OSS_DOMAIN_URL) !== false ) {
				$object_name = str_replace(OSS_DOMAIN_URL,'',$file);
				CrawlUtility::delFromQiniu($object_name);
				//CrawlUtility::delFromAliOss($object_name);
			}
			elseif( strpos($file,'http://imgproxy.135editor.com') !== false ) {
			    $object_name = str_replace('http://imgproxy.135editor.com','',$file);
			    CrawlUtility::delFromQiniu($object_name);
			    //CrawlUtility::delFromAliOss($object_name);
			}
			elseif( strpos($file,'http://cdn.135editor.com') !== false) {
			    $object_name = str_replace('http://cdn.135editor.com','',$file);
			    //CrawlUtility::delFromQiniu($object_name);
			    CrawlUtility::delFromAliOss($object_name);
			}
			elseif( strpos($file,'http://image.135editor.com') !== false) {
			    $object_name = str_replace('http://image.135editor.com','',$file);
			    CrawlUtility::delFromAliOss($object_name,'wx135');
			}
			//抓取的文件删除时只删除数据库记录，不删除oss文件，可能多个人在用。一个人的删除了oss文件，其余的人打不开。
// 			elseif( strpos($file,'http://image1.135editor.com') !== false) {
// 			    $object_name = str_replace('http://image1.135editor.com','',$file);
// 			    CrawlUtility::delFromAliOss($object_name,'wx135');
// 			}
// 			elseif( strpos($file,'http://remote.wx135.com/oss/view?d=') !== false) {
// 			    $url = urldecode( str_replace('http://remote.wx135.com/oss/view?d=','',$file) );
// 			    $object_name = 'cache/remote/'.base64_encode($url);
// 			    CrawlUtility::delFromAliOss($object_name,'wx135');
// 			}
			elseif( strpos($file,'wx135.com') !== false) {
			    $url = parse_url($file);
			    $object_name = $url['path'];
			    CrawlUtility::delFromAliOss($object_name,'wx135');
			}
			elseif( strpos($file,'https://mmbiz.qlogo.cn/') !== false) {
			    $object_name = 'cache/remote/'.base64_encode($file);
			    CrawlUtility::delFromAliOss($object_name,'wx135');
			}			
		}
	}
	
	public function deletes(){
	    $ids = $_REQUEST['ids'];
	    $filelist = $this->{$this->modelClass}->find('all', array(
	        'conditions' => array('id' => $ids, 'user_id' => $this->appUser['id']),
	        'recursive' => -1,
	    ));
	    foreach($filelist as $file) {
	        
	        $this->{$this->modelClass}->deleteAll(array('id' => $file['AppUploadfile']['id'], 'user_id' => $this->appUser['id']),true,true);
	        
	        $this->_unlink($file['AppUploadfile']['fspath']);
	        $this->_unlink($file['AppUploadfile']['mid_thumb']);
	        $this->_unlink($file['AppUploadfile']['thumb']);
	    }
	    echo json_encode(array('ret'=>0,'msg'=> __('Delete Successfully')));
	    exit;
	}
	
	public function delete($id = ''){
	    if(empty($id)) {
	        $id = $_REQUEST['id'];
	    }
	    
		$datainfo = $this->{$this->modelClass}->find('first', array(
				'conditions' => array('id' => $id, 'user_id' => $this->appUser['id']),
				'recursive' => -1,
		));
		if (empty($datainfo)) {
			echo json_encode(array('ret'=>-6,'msg'=> __('You cannot delete this data')));
			exit;
		}
		$this->_unlink($datainfo['AppUploadfile']['fspath']);
		$this->_unlink($datainfo['AppUploadfile']['mid_thumb']);
		$this->_unlink($datainfo['AppUploadfile']['thumb']);
		
		$this->{$this->modelClass}->deleteAll(array('id' => $id, 'user_id' => $this->appUser['id']),true,true);
		echo json_encode(array('ret'=>0,'msg'=> __('Delete Successfully')));
		exit;
	}
	
	/**
	 *
	 * @param unknown $aco such as  'controllers/AppUploadfiles'
	 */
	public function check(){
		$aco = $_GET['aco'];
		if($this->check_permition($aco)) {
			$watermarks = $this->appUser['UserSetting'];
			if(!empty($watermarks)) {
				foreach($watermarks as $k => $mark){
					if(!is_array($mark) || empty($mark['watermark_pos'])) {
						unset($watermarks[$k]); // 无水印的参数去除
					}
				}
			}
			echo json_encode(array('ret'=>1,'watermarks' => $watermarks));
			exit;
		}
		echo json_encode( array('ret'=> 0) );
		exit;
	}
	
	/**
	 * 裁剪图片
	 */
	public function crop(){
		
		$src = $_POST['src']?$_POST['src']:$_GET['src'];
		$this->set('src',$src);
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['w'] && $_POST['h'])
		{
			App::uses('ImageResize','Lib');
			$imageResize = new ImageResize();
			//$dst_w = $dst_h = 150;
			
			$max_width = 600;
			$jpeg_quality = 90;
			
			$mime = 'image/jpeg';
			$ext = 'jpg';
			
			if(strpos($src,'http') === false){
				$imageurl = $local_img = UPLOAD_FILE_PATH.$src;
				list($width_orig, $height_orig) = getimagesize($local_img);
				$mime = get_mime_type($local_img);
			}
			else{
				list($width_orig, $height_orig) = getimagesize($src);
				$mime = get_mime_type($src);
				$imageurl = $src;
			}
			
			if($mime == 'image/jpeg') {
				$img_r = @imagecreatefromjpeg($imageurl);
			}
			elseif($mime == 'image/gif') {
				$img_r = @imagecreatefromgif($imageurl);
				$ext = 'gif';
			}
			elseif($mime == 'image/png') {
				$img_r = @imagecreatefrompng($imageurl);
				$jpeg_quality = $jpeg_quality/10;
				$ext = 'png';
			}
			elseif($mime == 'image/bmp') {
				$img_r = @imagecreatefromwbmp($imageurl);
				$ext = 'bmp';
			}
			
// 			echo "===$mime=======$src====$local_img===";
			
			$ratio = $width_orig/$_POST['dw'];
			$dst_w = ($_POST['w']/$_POST['dw']) * $width_orig;
			$dst_h = ($_POST['h']/$_POST['dh']) * $height_orig;
			
			
			$dst_r = @imagecreatetruecolor( $dst_w, $dst_h );
			$color = imagecolorallocate($dst_r,255,255,255);   //分配一个白色背景
			imagefill($dst_r,0,0,$color);                 // 从左上角开始填充灰色
			if($mime == 'image/png') {
				imagecolortransparent ($dst_r,$color);
			}

			
			$src_x = $_POST['x']*$ratio;
			$src_y = $_POST['y']*$ratio;
			//$dst_w = 
// 			echo "-==$ratio===$dst_r,$img_r,0,0,$src_x,$src_y,$dst_w,$dst_h,$width_orig,$height_orig=====";exit;
		
// 			@imagecopyresampled($dst_r,$img_r,0,0,$src_x,$src_y, $dst_w,$dst_h,$width_orig,$height_orig);//$_POST['h']*$ratio
			
			@imagecopyresampled($dst_r,$img_r,0,0,$src_x,$src_y, $dst_w,$dst_h,$dst_w,$dst_h);
		
			
			$ret = array('ret' => 1);
			
			if(strpos($src,'http') === false){
				//本地图片
				if($mime == 'image/jpeg') {
					@imagejpeg($dst_r,$local_img,$jpeg_quality);
				}
				elseif($mime == 'image/gif') {
					@imagegif($dst_r,$local_img,$jpeg_quality);
				}
				elseif($mime == 'image/png') {
					@imagepng($dst_r,$local_img,$jpeg_quality);
				}
				elseif($mime == 'image/bmp') {
					@imagewbmp($dst_r,$local_img,$jpeg_quality);
				}
				
				$imageResize->resizefile($local_img,$local_img,$max_width);
				if( $_POST['watermark_img'] && $_POST['watermark_pos']) {
					$imageResize->watermark($local_img,$_POST['watermark_img'],$_POST['watermark_pos']);
				}
				elseif( $_POST['watermark_text'] && $_POST['watermark_pos']) {
					$imageResize->watermark_text($local_img,$_POST['watermark_text'],$_POST['watermark_pos']);
				}
				
				$filesize = filesize($local_img);
				
				$ret['url'] = Router::url($src,true);
			}
			else{
				if(preg_match('|http://img\d?\.wx135\.com/|i',$src ) || strpos($src,'http://image.135editor.com/') !== false ) {
					
					$ques = strpos($src,'?');
					if( $ques !== false ) {
						$src = substr($src,0,$ques);
					}
					$object_name = preg_replace('|http://img\d?\.wx135\.com/|i','',$src);
					$object_name = preg_replace('|http://image.135editor.com/|i','',$object_name);
					
					
					/* 不能非常准确的判断用户是否对一张图片具有操作权限，生成新的图片 */
					$paths = explode('/',$object_name);
					if( $paths[4] != $this->appUser['id'] ) { // else当路径用的第4个目录值不为用户编号时，生成新文件。防止覆盖掉了别人的文件
						$object_name = '/files/appusers/'.$this->app_id.'/'.intval($this->appUser['id']/10000).'/'.$this->appUser['id'].'/'.date('Ym').'/'.substr(md5($src),0,8).'_'.random_str(6).'.'.$ext;
					}
					else {
						$oldfile = $this->AppUploadfile->find('first',
						array('conditions'=> array('fspath'=>'http://img.wx135.com/'.$object_name,'user_id' => $this->appUser['id'],)));
					}
					
					mkdir_p(dirname(TMP.$object_name));
					
					if($mime == 'image/jpeg') {
						@imagejpeg($dst_r,TMP.$object_name,$jpeg_quality);
					}
					elseif($mime == 'image/gif') {
						@imagegif($dst_r,TMP.$object_name,$jpeg_quality);
					}
					elseif($mime == 'image/png') {
						@imagepng($dst_r,TMP.$object_name,$jpeg_quality);
					}
					elseif($mime == 'image/bmp') {
						@imagewbmp($dst_r,TMP.$object_name,$jpeg_quality);
					}
					
					$imageResize->resizefile(TMP.$object_name,TMP.$object_name,$max_width);					
					if( $_POST['watermark_img'] && $_POST['watermark_pos']) {
						$imageResize->watermark(TMP.$object_name,$_POST['watermark_img'],$_POST['watermark_pos']);
					}
					elseif( $_POST['watermark_text'] && $_POST['watermark_pos']) {
						$imageResize->watermark_text(TMP.$object_name,$_POST['watermark_text'],$_POST['watermark_pos']);
					}
					
					$filesize = filesize(TMP.$object_name);
					
					CrawlUtility::saveToAliOss(TMP.$object_name, $object_name,true,false,false,array('bucket_name'=>'wx135','domain_url'=>'http://image.135editor.com'));
					@unlink(TMP.$object_name);
					$ret['url'] = $src;
				}
				else{
					
					$object_name = '/files/appusers/'.$this->app_id.'/'.intval($this->appUser['id']/10000).'/'.$this->appUser['id'].'/'.date('Ym').'/'.substr(md5($src),0,8).'_'.random_str(6).'.'.$ext;
					mkdir_p(dirname(UPLOAD_FILE_PATH.$object_name));
					
					if($mime == 'image/jpeg') {
						@imagejpeg($dst_r,UPLOAD_FILE_PATH.$object_name,$jpeg_quality);
					}
					elseif($mime == 'image/gif') {
						@imagegif($dst_r,UPLOAD_FILE_PATH.$object_name,$jpeg_quality);
					}
					elseif($mime == 'image/png') {
						imagepng($dst_r,UPLOAD_FILE_PATH.$object_name,$jpeg_quality);
					}
					elseif($mime == 'image/bmp') {
						@imagewbmp($dst_r,UPLOAD_FILE_PATH.$object_name,$jpeg_quality);
					}
					$imageResize->resizefile(UPLOAD_FILE_PATH.$object_name,UPLOAD_FILE_PATH.$object_name,$max_width);
					if( $_POST['watermark_img'] && $_POST['watermark_pos']) {
						$imageResize->watermark(UPLOAD_FILE_PATH.$object_name,$_POST['watermark_img'],$_POST['watermark_pos']);
					}
					elseif( $_POST['watermark_text'] && $_POST['watermark_pos']) {
						$imageResize->watermark_text(UPLOAD_FILE_PATH.$object_name,$_POST['watermark_text'],$_POST['watermark_pos']);
					}
					$filesize = filesize(UPLOAD_FILE_PATH.$object_name);
					
					if( $url = CrawlUtility::saveToAliOss(UPLOAD_FILE_PATH.$object_name, $object_name,true,false,false,array('bucket_name'=>'wx135','domain_url'=>'http://image.135editor.com') ) ){
						@unlink(UPLOAD_FILE_PATH.$object_name);
					}
					else{
						$url = Router::url(UPLOAD_FILE_URL.$object_name,true);
					}
					
					$ret['url'] = $url;
				}
			}
			
			$this->AppUploadfile->save(array(
				'id' => $oldfile['AppUploadfile']['id'] ? $oldfile['AppUploadfile']['id'] : null,
				'fspath' => $ret['url'],
				'user_id' => $this->appUser['id'],
				'type' => $mime,
				'size' => $filesize,
			));
			
			
			echo json_encode($ret);
			exit;
		}
		
		if ($this->RequestHandler->isAjax() || isset($_GET['inajax'])) {
			// ajax 操作
			$this->layout = 'ajax';
		}
		
		$this->set('user_setting',$this->appUser['UserSetting']);
		
		$this->autoRender = true;
	}
	
	public function ueditor(){
		$action = $_GET['action'];	
		
		if($action != 'uploadimage') {
		    header('Content-Type: application/x-javascript');
		}
		if(in_array($action,array('uploadimage','uploadvideo','uploadscrawl','AppUploadfile'))) {
			if( $this->appUser['id']) {
				$role_ids = array();
				$role_ids[] = 2; //普通注册组
				if(is_array($this->appUser['Role'])) {
					foreach($this->appUser['Role'] as $role) {
						$role_ids[] = $role['id'];
					}
				}
				if(! $this->Acl->check(array('model'=>'Role','foreign_key'=>$role_ids), 'controllers/AppUploadfiles') ){
				    if($_REQUEST['domain']) {
				        echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
				    }
					echo json_encode(array('ret' => -1,'error'=> __('No Permission'),'state' =>  __('No Permission')));
					if($_REQUEST['domain']) {
					    echo "</body></html>";
					}
					exit;
				}
			}
			else{
			    if($_REQUEST['domain']) {
			        echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
			    }
				echo json_encode(array('ret' => -1,'error'=> __('You need to login'),'state' =>  __('You need to login')));
				if($_REQUEST['domain']) {
				    echo "</body></html>";
				}
				exit;
			}
		}
		
		switch ($action) {
			case 'config':
				$result =  '{"imageActionName":"uploadimage","imageFieldName":"upload","imageMaxSize":2048000,"imageAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"imageCompressEnable":true,"imageCompressBorder":1600,"imageInsertAlign":"none","imageUrlPrefix":"","imagePathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","scrawlActionName":"uploadscrawl","scrawlFieldName":"upload","scrawlPathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","scrawlMaxSize":2048000,"scrawlUrlPrefix":"","scrawlInsertAlign":"none","snapscreenActionName":"uploadimage","snapscreenPathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","snapscreenUrlPrefix":"","snapscreenInsertAlign":"none","catcherLocalDomain":["image1.135editor.com","image2.135editor.com","img.wx135.com","cdn.135editor.com","img.baidu.com"],"catcherUrl":"http://upload.135editor.com/uploadfiels/ueditor?action=catchimage","catcherActionName":"catchimage","catcherFieldName":"source","catcherPathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","catcherUrlPrefix":"","catcherMaxSize":2048000,"catcherAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"videoActionName":"uploadvideo","videoFieldName":"upload","videoPathFormat":"\/ueditor\/php\/upload\/video\/{yyyy}{mm}{dd}\/{time}{rand:6}","videoUrlPrefix":"","videoMaxSize":2048000,"videoAllowFiles":[".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid"],"fileActionName":"AppUploadfile","fileFieldName":"upload","filePathFormat":"\/ueditor\/php\/upload\/file\/{yyyy}{mm}{dd}\/{time}{rand:6}","fileUrlPrefix":"","fileMaxSize":2048000,"fileAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp",".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid",".rar",".zip",".tar",".gz",".7z",".bz2",".cab",".iso",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".pdf",".txt",".md",".xml"],"imageManagerActionName":"listimage","imageManagerListPath":"\/ueditor\/php\/upload\/image\/","imageManagerListSize":20,"imageManagerUrlPrefix":"","imageManagerInsertAlign":"none","imageManagerAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"fileManagerActionName":"listfile","fileManagerListPath":"\/ueditor\/php\/upload\/file\/","fileManagerUrlPrefix":"","fileManagerListSize":20,"fileManagerAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp",".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid",".rar",".zip",".tar",".gz",".7z",".bz2",".cab",".iso",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".pdf",".txt",".md",".xml"]}';
				break;
			/* 上传图片 */
			case 'uploadimage':				
				if(!empty($_FILES)) {
				    $_REQUEST['type'] = 'images';
				    $_REQUEST['return'] = 'ueditor';
				    if( WeixinUtility::$appId ) {
				        $_REQUEST['remote_type'] = 'wechatUploadimg';
				    }
    				//$_REQUEST['no_db'] = 0;
    				$_REQUEST['no_thumb'] = 1;
    				$result =  $this->upload();
				}
				break;
				/* 上传视频 */
			case 'uploadvideo':
				$_REQUEST['type'] = 'videos';
				$_REQUEST['return'] = 'ueditor';
				//$_REQUEST['no_db'] = 1;
				$_REQUEST['no_thumb'] = 1;
				$result =  $this->upload();
				break;
			case 'uploadword':			    
			    $result =  $this->wordToHtml();
			    break;
				/* 上传涂鸦 */
			case 'uploadscrawl':
				/* 上传文件  */
			case 'AppUploadfile':
				$_REQUEST['return'] = 'ueditor';
				//$_REQUEST['no_db'] = 0;
				$_REQUEST['no_thumb'] = 1;	
				$_POST['file_model_name'] = 'ueditor';
				$result =  $this->upload();
				break;
			/* 抓取远程文件 */
			case 'catchimage':
			    $source = $_POST['source'];
			    
			    if( empty($this->appUser['id']) || !is_array($source) || empty($source) ) {
			    	$result = json_encode(array(
			    			'state'=> '未登陆或请求地址出错'
			    	));
			    	break;
			    }
			    
			    $list = array();
			    
			    foreach ($source as $oldUrl) {

			        $imgUrl = str_replace('&amp;','&',$oldUrl);
			        //$imgUrl = str_replace('http://mmbiz.qpic.cn','https://mmbiz.qlogo.cn',$imgUrl);
			        $imgUrl = preg_replace('/&?wxfrom=\d+/','',$imgUrl);
			        $imgUrl = preg_replace('/&?wx_lazy=\d+/','',$imgUrl);
			        $imgUrl = preg_replace('/&?tp=[a-z]+/','',$imgUrl);
			        $imgUrl = preg_replace('/&?fr=[0-9a-z]+/i','',$imgUrl);
			        $imgUrl = preg_replace('/&?rd=[0-9a-z]+/i','',$imgUrl);
			        
			        $imgUrl = preg_replace('/\?&/','?',$imgUrl);
			        $imgUrl = preg_replace('/\?$/','',$imgUrl);
			        $referer = $imgUrl;
			        
			        if(strpos($imgUrl,'http://remote.wx135.com') !== false){ //已下载图片转换处理的图片跳过
			        	
			            $urlinfo = parse_url($imgUrl);
			            parse_str($urlinfo['query'],$query);
			            $wxurl = $query['d'];
			            if(!empty($wxurl)) {
				            /* 包含了多重remote.wx135.com的错误地址  */
				            while(strpos($wxurl,'http://remote.wx135.com/oss/view') !== false) {
				            	$urlinfo = parse_url($wxurl);
				            	parse_str($urlinfo,$query);
				            	if($query['d']) {
				            		$wxurl = $query['d'];
				            	}
				            }
				            
				            if(strpos($wxurl,'https://mmbiz.qlogo.cn/') !== false || strpos($wxurl,'http://mmbiz.qpic.cn/') !== false || strpos($imgUrl,'http://mmsns.qpic.cn') !== false ) {
				                $referer = 'http://mp.weixin.qq.com';
				            }
			            }
			            else{
			            	continue;
			            }
			            
			            $object_name = 'cache/remote/'.base64_encode($wxurl);
			            array_push($list, array(
				            "state" => 'SUCCESS',
				            "url" => 'http://image2.135editor.com/'.$object_name,
				            "source" => $oldUrl //htmlspecialchars($imgUrl)
			            ));
			            /*$content = CrawlUtility::aliOssExists($object_name,'wx135');
			            if($content) {			                		                
			                array_push($list, array(
    			                "state" => 'SUCCESS',
    			                "url" => 'http://image1.135editor.com/'.$object_name,
    			                "source" => $oldUrl //htmlspecialchars($imgUrl)
			                ));
			            }
			            else{
			                $url = CrawlUtility::saveImagesByUrl($imgUrl,$referer,array('resize'=>false,'bucket_name'=> 'wx135','domain_url'=>'http://image1.135editor.com/','object_name' => $object_name));
			                if($url) {
			                    array_push($list, array(
			                    "state" => 'SUCCESS',
			                    "url" => 'http://image1.135editor.com/'.$object_name,
			                    "source" => $oldUrl //htmlspecialchars($imgUrl)
			                    ));
			                }
			            }*/        
			            continue;
			        }
			        elseif( strpos($imgUrl,'wx135.com') !== false || strpos($imgUrl,'135editor.com') !== false ){ //已转换处理的图片跳过
			            continue;
			        }
			        
// 			        if(strpos($imgUrl,'http://mmbiz.qpic.cn') !== false) {//qpic转换成qlogo
// 			            $imgUrl = str_replace('http://mmbiz.qpic.cn','https://mmbiz.qlogo.cn',$imgUrl);
// 			        }
			        
			        //else			        
			        if( strpos($imgUrl,'https://mmbiz.qlogo.cn') !== false || strpos($imgUrl,'http://mmbiz.qpic.cn') !== false || strpos($imgUrl,'http://mmsns.qpic.cn') !== false ){
			            $referer = 'http://mp.weixin.qq.com';
			            $object_name = 'cache/remote/'.base64_encode($imgUrl);
			            $url = 'http://image2.135editor.com/'.$object_name;
			            /*if( CrawlUtility::aliOssExists($object_name,'wx135') ) {
			                $url = 'http://image1.135editor.com/'.$object_name;
			            }
			            else{
			                $url = CrawlUtility::saveImagesByUrl($imgUrl,$referer,array('resize'=>false,'bucket_name'=> 'wx135','domain_url'=>'http://image1.135editor.com/','object_name' => $object_name));
			            }*/
			            
			            if($url) {
			                array_push($list, array(
    			                "state" => 'SUCCESS',
    			                "url" => $url,
    			                "source" => $oldUrl //htmlspecialchars($imgUrl)
			                ));
			            }
			        }
			        
			        /*else{ // 其余地址同步到微信
			            if( !empty(WeixinUtility::$appId) ){
			                $filepath = CrawlUtility::saveImagesByUrl($imgUrl,$imgUrl,array('oss'=>false,'resize'=>false));
			                if($filepath) {
			                    $info = WeixinUtility::uploadImg( UPLOAD_FILE_PATH . $filepath);
			                    if($info['url']) {
			                        $object_name = 'cache/remote/'.base64_encode($info['url']);
			                        $url = CrawlUtility::saveToAliOss( UPLOAD_FILE_PATH . $filepath , $object_name,true,false,false,array('bucket_name'=> 'wx135','domain_url'=>'http://image1.135editor.com/'));
			                        if($url) {
			                            array_push($list, array(
    			                            "state" => 'SUCCESS',
    			                            "url" => 'http://image1.135editor.com/'.$object_name,
    			                            "source" => $oldUrl// htmlspecialchars($imgUrl)
			                            ));
			                        }
			                    }
			                    else{
			                        @unlink( UPLOAD_FILE_PATH . $filepath );
			                    }
			                }
			            }
			            elseif( count($this->appUser['role_id']) > 1 ){			                
			                $url = CrawlUtility::saveImagesByUrl($imgUrl,'http://mp.weixin.qq.com',array('oss'=>true,'resize'=>false));
			                if($url) {
			                    // 付费用户自动中转下载其它站点图片,成功下载后替换图片地址。
			                    array_push($list, array(
    			                    "state" => 'SUCCESS',
    			                    "url" => $url,
    			                    "source" => $oldUrl//htmlspecialchars($imgUrl)
			                    ));
			                }
			                continue;			                
			            }
			        }*/
			    }
			    /* 返回抓取数据 */
			    $result = json_encode(array(
			        'state'=> count($list) ? 'SUCCESS':'ERROR',
			        'list'=> $list
			    ));
			    
			    break;
				/* 列出图片 */
			case 'listimage':
				$this->loadModel('EditorStyle');
				
				$size = $_GET['size'] ? $_GET['size'] : 12;
				$page = $_GET['start']/$size + 1;
				
				$conditions = array('EditorStyle.cate_id >='=>50, 'EditorStyle.status' => 1 );
				if($_GET['type'] == 'favor'){
					$images = $this->EditorStyle->find('all',array(
							'conditions' => $conditions,
							'limit' => $size,
							'page' => $page,
							'joins' => array(array(
								'table' => 'favorites',
								'alias' => 'Favorite',
								'type' => 'inner',
								'conditions' => array('EditorStyle.id=Favorite.data_id','Favorite.model'=>'EditorStyle','Favorite.creator_id'=>$this->appUser['id']),
							)),
					));
						
					$total =  $this->EditorStyle->find('count',array(
							'conditions' => $conditions,
							'order' => 'recommend desc,sort desc',
							'recursive' => -1,
							'joins' => array(array(
									'table' => 'favorites',
									'alias' => 'Favorite',
									'type' => 'inner',
									'conditions' => array('EditorStyle.id=Favorite.data_id','Favorite.model'=>'EditorStyle','Favorite.creator_id'=>$this->appUser['id']),
							)),
					));
				}
				else{
					if($_GET['type'] == 'bg') {
						$images = $this->EditorStyle->find('all',array(
						    'conditions' => array(
						        'EditorStyle.cate_id' => 1,
						        'EditorStyle.status' => 1,
						        'EditorStyle.coverimg <>' => '', 
						    ),
						    'joins' => array(
						        array(
						            'table' => 'tag_relateds',
						            'alias' => 'TagRelated',
						            'type' => 'inner',
						            'conditions' => array(
						                'TagRelated.relatedid = EditorStyle.id',
						                'TagRelated.relatedmodel'=>'EditorStyle',
						                'TagRelated.tag_id' => 225, //背景标签
						                
						            ),
						        )
						    ),
						    'limit' => $size,
						    'page' => $page,
						));
							
						$total =  $this->EditorStyle->find('count',array(
						    'conditions' => array(
						        'EditorStyle.cate_id' => 1,
						        'EditorStyle.status' => 1,
						        'EditorStyle.coverimg <>' => '', 
						    ),
						    'joins' => array(
						        array(
						            'table' => 'tag_relateds',
						            'alias' => 'TagRelated',
						            'type' => 'inner',
						            'conditions' => array(
						                'TagRelated.relatedid = EditorStyle.id',
						                'TagRelated.relatedmodel'=>'EditorStyle',
						                'TagRelated.tag_id' => 225, //背景标签
						                
						            ),
						        )
						    ),
						));
						
						
					}
					else{
					    if($_GET['type'] == 'bggif'){
					        $conditions = array('EditorStyle.cate_id'=>52);
					    }
					    elseif($_GET['type'] == 'split'){
					        $conditions = array('EditorStyle.cate_id'=>53);
					    }
					    elseif($_GET['type'] == 'guide'){
					        $conditions = array('EditorStyle.cate_id'=>56);
					    }
					    elseif($_GET['type'] == 'festival'){
					        $conditions = array('EditorStyle.cate_id'=>54);
					    }
					    elseif($_GET['type'] == 'gif'){
					        $conditions = array('EditorStyle.cate_id'=>55);
					    }
					    $images = $this->EditorStyle->find('all',array(
					        'conditions' => $conditions,
					        'limit' => $size,
					        'page' => $page,
					    ));
					    
					    $total =  $this->EditorStyle->find('count',array(
					        'conditions' => $conditions,
					    ));
					}
				}
				
				$result = array(
					'state' => 'SUCCESS',
					'list' => array(),
					'start' => $_GET['start'],
					'total' => $total,
				);
				foreach($images as $item){
					$result['list'][] = array(
							'id'=> $item['EditorStyle']['id'],
							'title'=> $item['EditorStyle']['name'],
							'url'=> $item['EditorStyle']['coverimg'].'?imageView2/2/w/200', // 显示缩略图。
							'mtime'=>1400203383,
					);
				}				
				$result = json_encode($result);//'{"state":"SUCCESS","list":[{"url":"\/server\/ueditor\/upload\/image\/3 2.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/26.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/25.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/24.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/23.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/22.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/21.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/20.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/2.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/19.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/18.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/17.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/16.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/15.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/14.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/13.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/12.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/11.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/10.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/1.jpg","mtime":1400203383}],"start":"0","total":29}';
				break;
				/* 列出文件 */
			case 'listfile':
				break;
			default:
				$result = json_encode(array(
				'state'=> '请求地址出错'
						));
						break;
		}
		
		/* 输出结果 */
		if (isset($_GET["callback"])) {
		    if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
		        echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
		    } else {
		        echo json_encode(array(
		            'state'=> 'callback参数不合法'
		        ));
		    }
		}
		else{
		    echo $result;
		}
		exit;
	}
	
	
	public function wordToHtml() {
	    
	    header("Access-Control-Allow-Origin: *");
	    
	    $source = $_FILES['textfile']['tmp_name'];
	    
	    $ext =  strtolower(end(explode('.', $_FILES['textfile']['name'])));
	    
	    if( ! in_array($ext,array('doc','docx','rtf','xls','xlsx','ppt','pptx','pdf','txt')) ) {
	        $result = json_encode(array(
	            "state" => '仅支持word,excel,ppt,txt,pdf文件',
	            "error" => '仅支持word,excel,ppt,txt,pdf文件',
	            "ret" => -1,
	        ));
	        
	        if($_GET['return'] == 'htmlspecialchars'){
	            echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>".$result."</body></html>";
	        }
	        else{
	            echo $result;
	        }
	        
	        exit;
	    }
	    else if(empty($this->appUser['id'])  || count(array_intersect(array(8,9,10,11,12),$this->appUser['role_id'])) == 0) {
	        $result = json_encode(array(
	            "state" => '您需要付费后，才可以导入word文档。<a href="http://www.135plat.com/" target="_blank">开通付费</a>，<a target="_blank" href="http://www.135editor.com/books/chapter/1/51">查看详情</a>',
	            "error" => '您需要付费后，才可以导入word文档。<a href="http://www.135plat.com/" target="_blank">开通付费</a>，<a target="_blank" href="http://www.135editor.com/books/chapter/1/51">查看详情</a>',
	            "ret" => -1,
	        ));
	        if($_GET['return'] == 'htmlspecialchars'){
	            echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>".$result."</body></html>";
	        }
	        else{
	            echo $result;
	        }
	        exit;
	    }
	    
	    $random_str = random_str(12);
	    $source_file = DATA_PATH.$random_str.'.'. $ext;
	    
	    move_uploaded_file($source,$source_file);
	    
	    $content = ''; $state = 'SUCCESS';
	    // 8 初级，10 中级，9高级
	    if( in_array($ext,array('doc','docx','rtf','xls','xlsx'))  &&  count(array_intersect(array(8,9,10,11,12),$this->appUser['role_id'])) > 0 ) {
	        
	        $cmd = 'soffice --headless --invisible --accept="socket,port=8100;urp;" --display :1 --convert-to html --outdir "'.DATA_PATH.'" '.$source_file;
	        $ret =exec($cmd,$retval);
	        
	        $html_file = DATA_PATH.$random_str.'.html';
	        $content = file_get_contents($html_file);
	        
            App::uses('ImageResize','Lib');
            // 将base64编码的图片内容，存储为图片文件 data:image/png;base64,
            // 图片内容太大时，preg_replace_callback无法操作成功，结果返回空，换用for循环操作。
            // for循环操作如果不行，尝试fgets逐行读取内容操作
            //$content = preg_replace_callback('|<img\s+src="data:image/(\w+);base64,(.+?)"|is',array($this,'_saveImage'),$content);
            $length = strlen($content);
            $imgtype=$imgcontent = '';
            $html = '';
            for($i=0; $i<$length; $i++) {
                if($content[$i]=='<' && $content[$i+1]=='i' && $content[$i+2]=='m' && $content[$i+3]=='g' && $content[$i+4]==' ') {
                    if( '<img src="data:image/' == substr($content,$i,21) ) {
                        for( $j=$i+21; $j<$length && $content[$j]!=';'; $j++ ) {
                            $imgtype .= $content[$j];
                        }
                        // $j=$j+7 skip "base64,"
                        for($j=$j+7; $j<$length && $content[$j]!='"'; $j++) {
                            $imgcontent .= $content[$j];
                        }
                        
                        $imgcontent = base64_decode($imgcontent);
                        if( strlen($imgcontent) > 1024000 ) {
                            $html .= '<p class="135editor" style="align:center;margin:30px 0px 0px;color:red;">提示：此处图片大于1M，请手动上传</p><img src="about:blank" alt="图片大于1M，请手动上传。双击设置图片" ';
                        }
                        else{
                            $url = $this->_saveImageContent($imgtype,$imgcontent);
                            if($url) {
                                $html .= '<img src="'.$url.'" ';
                            }
                        }
                        $i = $j;
                        $imgtype=$imgcontent = '';
                        continue;
                    }
                }
                $html .= $content[$i];
            }
            
            $content = $html;
            if(preg_match("|<body.*?>(.+?)</body>\s*</html>|is",$content,$matches)) { // 只获取body中的部分。
                $content = $matches[1];
            }
            
	        unlink($html_file);
	    }
	    else if( in_array($ext,array('ppt','pptx','pdf'))  &&  count(array_intersect(array(9,10,11,12),$this->appUser['role_id'])) > 0 ) {
	        $pdf_file = $source_file;
	        if($ext != 'pdf') {
	            $cmd = 'soffice --headless --invisible --accept="socket,port=8100;urp;" --display :1 --convert-to pdf --outdir "'.DATA_PATH.'" '.$source_file;
	            $ret =exec($cmd,$retval);
	            $pdf_file = DATA_PATH.$random_str.'.pdf';
	        }
	        $image_file = DATA_PATH.$random_str.'.jpg';
// 	        $cmd = 'convert -verbose -density 300 -sharpen 0x1.0 -quality 100 -trim -resize 900 "'.DATA_PATH.'" '.$pdf_file.'  "'.$image_file.'"';
	        // 在处理时间与处理的图片清晰度之间做一个平衡。
	        $cmd = 'convert -verbose -density 150 -quality 100 -trim "'.DATA_PATH.'" '.$pdf_file.'  "'.$image_file.'"';
	        
	        $ret =exec($cmd,$retval);
	        
	        if( file_exists($image_file) ) {
                $ret = WeixinUtility::uploadImg( $image_file );
                if($ret['url']) {
                    $url = 'http://image2.wx135.com/cache/remote/'.base64_decode($ret['url']);
                    @unlink($image_file);//上传微信成功后，删除本地图片
                }
	            else {
	            	$url = CrawlUtility::saveToQiniu($image_file, '/uploadpdf/'.date('Ym').'/'.date('d').'_'.$random_str.'.jpg');
	                //$url = CrawlUtility::saveToAliOss($image_file, '/uploadpdf/'.date('Ym').'/'.date('d').'_'.$random_str.'.jpg');
	            }
	            if($url) {
	                $content .= '<p><img src="'.$url.'" remark="图片为使用135编辑器导入PPT/PDF文档生成"></p><p><br></p>';
	            }
	        }
	        
	        for($i = 0;;$i++) {
	            $pdf_img = DATA_PATH.$random_str.'-'.$i.'.jpg';
	            if( file_exists($pdf_img) ) {
	                
	                $ret = WeixinUtility::uploadImg( $pdf_img );
	                if($ret['url']) {
	                    $url = $ret['url'];
	                    @unlink($image_file);//上传微信成功后，删除本地图片
	                }
	                else {
	                	$url = CrawlUtility::saveToQiniu($pdf_img, '/uploadpdf/'.date('Ym').'/'.date('d').'_'.$random_str.'-'.$i.'.jpg');
	                    //$url = CrawlUtility::saveToAliOss($pdf_img, '/uploadpdf/'.date('Ym').'/'.date('d').'_'.$random_str.'-'.$i.'.jpg');
	                }
	                if( $url ) {
	                    $content .= '<p style="text-align:center;"><img src="'.$url.'" remark="图片为使用135编辑器导入PPT/PDF文档生成"></p><p><br></p>';
	                }
	            }
	            else{
	                break;
	            }
	        }
	        @unlink($pdf_file);
	    }
	    elseif( $ext == 'txt'  || $_FILES['textfile']['type'] == 'text/plain' ) {
	        App::uses('Charset', 'Lib');
	        $content = file_get_contents($source_file);
	        if(Charset::is_gbk($content)) {
	            $content = Charset::gbk_utf8($content);
	        }
	        $arr = explode("\n",$content);
	        $content = '<p>'.implode('</p><p>',$arr).'</p>';
	    }
	    else{
	        $content = ''; $state = '请检查是否有权限上传此类型文件';
	    }
	    
	    
		@unlink($source_file);
		$content = str_replace(array("\r\n","\r","\n"),array('','',''), $content);
		
		$content = preg_replace('/line-height:.+?(;|")/i','\\1',$content); //去除原来的行高
		$content = preg_replace('/position:.+?(;|")/i','\\1',$content); //去除绝对定位
		
		$retArr =  array(
		    "state" => $state,
		    "content" => html_entity_decode($content),
		);
	
		$result = json_encode($retArr,JSON_UNESCAPED_UNICODE);
		if($_GET['jsoncallback']){
		   $result = $_GET['jsoncallback'] . '(' . $result . ');';
		}
		elseif($_GET['return'] == 'urlencode'){
			echo urlencode($result);
		}
		elseif($_GET['return'] == 'htmlspecialchars'){
			//echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>".htmlspecialchars($result)."</body></html>";
		    echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>".str_replace(array('<','>'),array('&lt;','&gt;'),$result)."</body></html>";
		}
		else{
			echo $result;
		}		
		//echo '<textarea>'.htmlspecialchars($result).'</textarea>';
		//echo '<textarea>'.($result).'</textarea>';
		exit;
	    
	    /*
	     * phpword转换的文档内容，图片没有处理都丢失了，不完善 2015.9.4
	    require_once ROOT.'/lib/Vendor/PhpWord/Autoloader.php';
	    \PhpOffice\PhpWord\Autoloader::register();
	    //\PhpOffice\PhpWord\Settings::loadConfig();
	    \PhpOffice\PhpWord\Settings::setZipClass(\PhpOffice\PhpWord\Settings::PCLZIP);
	    
	        
	    
	    if($_FILES['textfile']['type'] == 'application/msword' || in_array($ext,array('doc','docx'))) {
	        if($ext == 'doc') {
	            $phpWord = \PhpOffice\PhpWord\IOFactory::load($destination, 'MsDoc');
	        }
	        else{
	            $phpWord = \PhpOffice\PhpWord\IOFactory::load($destination);
	        }
	         //, 'MsDoc'
// 	        $phpWord->save('135editor.html','HTML',true);
	        $htmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
	        echo $html =  $htmlWriter->getContent();
	        
	        $phpWord->save(ROOT.'/test.docx','Word2007',false);
	    }
	    //unlink($destination);*/
	   
	    
	    
	}
	
	private function _saveImage($matches){
	    $ext = 'jpg';
	    if($matches[1] == 'png') {
	        $ext = 'png';
	    }
	    elseif($matches[1] == 'gif') {
	        $ext = 'gif';
	    }
	    elseif($matches[1] == 'bmp') {
	        $ext = 'bmp';
	    }
	    
	    $file_name = md5(substr($matches[2],0,100)).'.'.$ext;
	    
	    $img_file = TMP_FILES.$file_name;
	    file_put_contents($img_file, base64_decode($matches[2]));
	    
	    App::uses('ImageResize','Lib');
		$image = new ImageResize();
		$width = 900;
		$image->resizefile($img_file,$img_file,$width);
		
		$ret = WeixinUtility::uploadImg( $img_file );
		if($ret['url']) {
		    $url = $ret['url'];
		    @unlink($img_file);//上传微信成功后，删除本地图片
		}
		else {
		    $url = CrawlUtility::saveToAliOss($img_file, '/uploadword/'.date('Ym').'/'.$file_name);
		}
		if( $url ) {
		    return '<img src="'.$url.'" ';
		}
		else{
		    @unlink($img_file);
		    return $matches[0];
		    //return '<img src="data:image/'.$matches[1].';base64,'.$matches[2].'"';
		}
	}
	
	private function _saveImageContent($type,$content){
	    $ext = 'jpg';
	    if($type == 'png') {
	        $ext = 'png';
	    }
	    elseif($type == 'gif') {
	        $ext = 'gif';
	    }
	    elseif($type == 'bmp') {
	        $ext = 'bmp';
	    }
	     
	    $file_name = CKString::uuid().'.'.$ext;
	     
	    $img_file = TMP.$file_name;
	    file_put_contents($img_file, $content);
	     
	    App::uses('ImageResize','Lib');;
	    $image = new ImageResize();
	    $width = 900;
	    $image->resizefile($img_file,$img_file,$width);
	
	    $ret = WeixinUtility::uploadImg( $img_file );
	    if($ret['url']) {
	        //$url = $ret['url'];
	        $url = 'http://image2.wx135.com/cache/remote/'.base64_decode($ret['url']);
	        @unlink($img_file);//上传微信成功后，删除本地图片
	    }
	    else {
	    	$url = CrawlUtility::saveToQiniu($img_file, '/upload/'.date('Ym').'/'.$file_name);
	        //$url = CrawlUtility::saveToAliOss($img_file, '/uploadword/'.date('Ym').'/'.$file_name);
	    }
	    if( $url ) {
	        return $url;
	    }
	    else{
	        @unlink($img_file);
	        return null;
	    }
	}
	
	
	public $maxFileSize = 2048000;
	
	/**
	 * 内部检验上传权限
	 * @return string
	 */
	public function upload() {
	    $this->autoRender = false;
		if(empty($this->appUser['id'])){
			if($_REQUEST['return']=='ckeditor'){
				$funcNum = $_REQUEST['CKEditorFuncNum'];
				echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "", "'.__('You need to login').'");</script>';
			}
			else{ // error for ueditor 
			    $result = array('ret' => -1,'error'=> __('You need to login'),'state' =>  __('You need to login'));
			    if($_REQUEST['domain']) {
			        echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
			        echo json_encode($result);
			        echo "</body></html>";
			    }
			    else{
			        $this->ajaxOutput($result);
			    }
			}
			exit;
		}
		
		if( WeixinUtility::$appId ) {
		    $_REQUEST['remote_type'] = 'wechatUploadimg';
		}
		
		if( $_REQUEST['remote_type'] == 'wechat' ) { // 当上传类型不为微信时才检查上传权限
		    if( empty(WeixinUtility::$appId) ) {
		            $this->ajaxOutput(array('ret' => -2001,'status' => -1,'error'=> __('需要先微信授权后可上传微信图片'),'state' =>  __('需要先微信授权后可上传微信图片')));
		            exit;
		    }
		}
		elseif( ($_REQUEST['return'] == 'xiuxiu' || $_REQUEST['remote_type'] == 'wechatUploadimg') && !$this->check_permition('controllers/AppUploadfiles') ) {
		    // 编辑图片时检查权限
			$this->ajaxOutput(array('ret' => -2002,'status' => -1,'error'=> __('You are not allowed to perform this operation'),'state' =>  __('You are not allowed to perform this operation')));
			exit;
		}
		/*else{
		    $wxinfo = $this->Session->read('User.wxinfo');
		    if( empty($wxinfo)  && count($this->appUser['role_id']) == 1) {
		        echo json_encode(array('ret' => -1,'status' => -1,'error'=> __('免费用户需要先微信公众号授权后才可上传图片'),'state' =>  __('免费用户需要先微信公众号授权后才可上传图片')));
		        exit;
		    }
		}*/
		/*$month_num = $this->AppUploadfile->find('count',array(
		    'conditions' => array(
		        'user_id' => $this->appUser['id'],
		        'created >' => date('Y-m').'-01',
		    ),
		));
		
		if( in_array(9,$this->appUser['role_id']) || in_array(12,$this->appUser['role_id']) ) { //高级与企业 1000
		    if( $month_num >= 3000) {
		        if($_REQUEST['domain']) {
		            echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
		        }
		        echo json_encode(array('ret' => -2003,'status' => -1,'error'=> '上传太多了，黄金VIP每月允许上传3000张，已上传'.$month_num.'张，请删除无用文件','state' =>  '上传太多了，黄金VIP每月允许上传3000张，已上传'.$month_num.'张，请删除无用文件'));
		        if($_REQUEST['domain']) {
		            echo "</body></html>";
		        }
		        exit;
		    }
		}
		elseif( in_array(10,$this->appUser['role_id']) ){
		    if( $month_num >= 1000) {
		        if($_REQUEST['domain']) {
		            echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
		        }
		        echo json_encode(array('ret' => -2004,'status' => -1,'error'=> '上传太多了，白银VIP每月允许上传1000张，已上传'.$month_num.'张，请升级会员','state' =>  '上传太多了，白银VIP每月允许上传1000张，已上传'.$month_num.'张，请升级会员或删除本月已上传的无用文件'));
		        if($_REQUEST['domain']) {
		            echo "</body></html>";
		        }
		        exit;
		    }
		}
		elseif( in_array(8,$this->appUser['role_id']) ){
		    if( $month_num >= 300) {
		        if($_REQUEST['domain']) {
		            echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
		        }
		        echo json_encode(array('ret' => -2005,'status' => -1,'error'=> '上传太多了，VIP用户每月允许上传300张，已上传'.$month_num.'张，请升级会员。','state' =>  '上传太多了，VIP用户每月允许上传300张，已上传'.$month_num.'张，请升级会员或删除本月已上传的无用文件'));
		        if($_REQUEST['domain']) {
		            echo "</body></html>";
		        }
		        exit;
		    }
		}
		else {
		    if( $month_num >= 100 ) {
		        if($_REQUEST['domain']) {
		            echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
		        }
		        echo json_encode(array('ret' => -2006,'status' => -1,'error'=> '上传太多了，免费用户每月允许上传100张，已上传'.$month_num.'张，请升级会员','state' =>  '上传太多了，免费用户每月允许上传100张，已上传'.$month_num.'张，请升级会员' ));
		        if($_REQUEST['domain']) {
		            echo "</body></html>";
		        }
		        exit;
		    }
		}*/
		
		/* $file_post_name 默认为upload，
		 ckeditor传入的文件字段名为upload。但无$_POST ['file_post_name']
		*/
		$file_post_name = $_POST['file_post_name']?$_POST['file_post_name']:'upload';
		
		if($this->params ['form'] [$file_post_name] ['size'] > $this->maxFileSize){
			unlink($this->params ['form'] [$file_post_name] ['tmp_name']);
			$this->ajaxOutput(array('ret' => -2007,'error'=> __('File is too large'),'state' =>  __('File is too large')));
			exit;
		}
		
		$info = array ();
		$info ['status'] = '0';
		$info ['fieldname'] = $file_post_name;
		if (isset ( $this->params['form'] [$file_post_name] )) {
		    
			// upload the file
			if(!empty($_REQUEST['no_thumb']) || $_REQUEST['no_db'] ){ //图片不自动生成缩略图
				$this->SwfUpload->gen_thumb = false;
			}
						
			if($_REQUEST['remote_type']) {
			    $this->SwfUpload->setRemoteType( $_REQUEST['remote_type'] ) ;
			}
			
			if($_GET['watermark']) { // 勾选了自动加水印
				
				if( empty($this->appUser['UserSetting']) ){
					$this->loadModel('UserSetting');
					$this->appUser['UserSetting'] = $this->UserSetting->get($this->appUser['id']);
				}
				
				$watermark = $this->appUser['UserSetting'];
				$current_wxinfo = $this->Session->read('User.wxinfo');
				if(!empty($current_wxinfo)){ // 全局水印，或者当前操作公众号的水印。
					$wx_id = $current_wxinfo['Wx']['id']; 
					if(!empty($this->appUser['UserSetting'])) {
						$watermark = $this->appUser['UserSetting'][$wx_id];
					}
				}
				
				if( !empty($watermark) && $watermark['watermark_pos'] ) {
					$this->SwfUpload->watermark_pos = $watermark['watermark_pos'];
					$this->SwfUpload->watermark_img = $watermark['watermark'];
					$this->SwfUpload->watermark_text = $watermark['watermark_text'];
				}
			}
			
			/*
			 * 编辑时无需覆盖原文件，生成新文件即可。
			 * 1. 更新AppUploadfiles表中的记录麻烦
			 * 2. 覆盖了旧的文件，可能影响历史文件的图片展示
			 * 3. 用户自行维护删除即可
			 * 4. 未被使用占用流量的图片消耗费用非常低，可以忽略不计，主要是流量贵
			 if(preg_match('|http://img\d?\.wx135\.com/|i',$_REQUEST['url'] ) || strpos($_REQUEST['url'],'http://image.135editor.com/') !== false ) {
			    	
			    $ques = strpos($src,'?');
			    if( $ques !== false ) {
			        $src = substr($src,0,$ques);
			    }
			    //$object_name = preg_replace('|http://img\d?\.wx135\.com/|i','',$src);
			    $object_name = preg_replace('|http://image.135editor.com/|i','',$object_name);
			    
			    $paths = explode('/',$object_name);
			    if( $paths[3] == $this->appUser['id'] ) { // else当路径用的第4个目录值不为用户编号时，生成新文件。防止覆盖掉了别人的文件
			        $oldfile = $this->AppUploadfile->find('first',
			            array('conditions'=> array('fspath'=>'http://image.135editor.com/'.$object_name,'user_id' => $this->appUser['id'],)));
			        
			        $this->data['AppUploadfile']['id'] = $oldfile['AppUploadfile']['id'];
			    }
			    
			}
			*/    
			    
			
			if(!empty($_REQUEST['save_folder'])){ //指定保存位置
				$this->SwfUpload->uploadpath = UPLOAD_FILE_PATH.$_POST['save_folder'];
			}
			else{//if(!empty($_REQUEST['type'])){ //ckeditor传入了指定的类型，如images,flashes,videos
				//if( $_REQUEST['no_db'] ){ // 不保存到数据库时，按用户id号上传到用户个人目录
					$this->SwfUpload->setSavePath( 'appusers/'.$this->app_id.'/'.intval($this->appUser['id']/10000).'/'.$this->appUser['id'].'/'.date('Ym'));
				//}
				//else{
				//	$this->SwfUpload->setSavePath($_REQUEST['type']);
				//}				
			}
			
			if( !empty($_REQUEST['watermark']) ){
			
			}
			
			
			$this->SwfUpload->file_post_name = $file_post_name;
			
			if ( $fileinfo = $this->SwfUpload->upload() ) {
				if( $_REQUEST['no_db'] ){// 不保存到数据库，在ckeditor中上传文件的场景					
					$info ['status'] = '1';
					$info =array_merge($info,$fileinfo);
					$url = $fileinfo['fspath'];
					if ( strpos($url,'https://') ===false && strpos($url,'http://') ===false  ) {
						$file_url = UPLOAD_FILE_URL.str_replace ( '//', '/', $url );
					} else {
						$file_url = $url;
					}


					if(is_image($file_url)){
						$info['message'] = '<div class="col-sm-12"><a href="'.$file_url.'" title="'.__( 'Preview').'" target="_blank"><img src="'.$file_url.'" style="max-height:120px"/></a></div>';
					}
					else{
						$info['message'] = '<div class="col-sm-12"><a href="'.$file_url.'" target="_blank">'.__( 'Preview').'</a></div>';
					}
				}
				else{
					$file_model_name = $_POST['file_model_name'];
					$modelname = Inflector::classify ( $this->name );
					$this->data[$modelname]['modelclass'] = $file_model_name;
					$this->data[$modelname]['data_id'] = $_POST['data_id'];
					$this->data[$modelname]['app_id'] = $_REQUEST['little_id'];
					$this->data[$modelname]['user_id'] = $this->appUser['id'];
					$this->data[$modelname]['fieldname'] = $file_post_name;
					$this->data[$modelname]['name'] = $fileinfo['filename'];
					$this->data[$modelname]['size'] = $this->params ['form'] [$file_post_name] ['size'];
					$this->data[$modelname]['fspath'] = $fileinfo['fspath'];
					$this->data[$modelname]['type'] = $fileinfo['file_type'];
					
					$item_css = $_POST['item_css'];
					
					if (empty($_REQUEST['no_thumb']) && 'image' == substr ($fileinfo['file_type'], 0, 5 )) {
						$this->data[$modelname]['thumb'] = $fileinfo['thumb'];
						$this->data[$modelname]['mid_thumb'] = $fileinfo['mid_thumb'];
					}
					
					
					if (! ($file = $this->AppUploadfile->save ( $this->data ))) {
						$info['message'] = $this->SwfUpload->filename . ' Database save failed'; // 保存记录时失败
					} else {
						$info ['status'] = '1';
						$file_id = $this->AppUploadfile->getLastInsertId ();
						
						//上传文章素材封面成功时，删除已有的封面记录，同时删除素材同步记录中的原同步的封面media_id
						//if($_POST['data_id']){
						//    $this->loadModel('WxmsgSynclog');
						//    $this->WxmsgSynclog->updateAll(array('thumb_media_id'=>null),array('data_id'=>$_POST['data_id']));
						//}
						
						$info ['id'] = $file_id;

						$info ['fieldid'] = $fieldid = Inflector::camelize($file_model_name).Inflector::camelize($file_post_name);

						$info['message'] = '<div class="'.$item_css.' upload-fileitem" id="upload-file-'.$file_id.'">';

						//$image_url = $this->data[$modelname]['thumb'] ? $this->data[$modelname]['thumb'] : $this->data[$modelname]['fspath'];
						$image_url = $this->data[$modelname]['fspath'];
						
						if ( strpos($image_url,'https://') ===false && strpos($image_url,'http://') ===false  ) {
							$file_url = UPLOAD_FILE_URL.str_replace ( '//', '/', $image_url );
						} else {
							$file_url = $image_url;
						}
						
						$file_size = getHumanFileSize($this->data[$modelname]['size']);
						if ('image' == substr ( $this->data[$modelname]['type'], 0, 5 )) {
							
							$info['message'] .='<a title="'.($this->data[$modelname]['name']).'" href="'.Router::url('/app_uploadfiles/download/'.$file_id).'" target="_blank"><img src="'.$file_url.'"/><small>'.$file_size.'</small></a>';
						}
						else{
							$info['message'] .='<a title="'.($this->data[$modelname]['name']).'" href="'.Router::url('/app_uploadfiles/download/'.$file_id).'" target="_blank"><i class="glyphicon glyphicon-cloud-download"></i><small>'.$file_size.'</small></a>';
						}
						$info['message'] .= '<i class="glyphicon glyphicon-remove remove" data-id="'.$file_id.'" title="'.lang('remove this file').'"></i>';
						$info['message'] .= '<input type="hidden" name="data[AppUploadfile][' . $file_id . '][id]" value="' . $file_id . '">';
						
						// 使用 $this->request->webroot 连接在图片前面，而不用Router::url，避免后台添加图片时，文件都带上了 /manage/路径  
						
						$info['message'] .= '</div>';
						
						$info = array_merge($info,$this->data[$modelname]);
					}
				}
			} else {
				$info['message'] = 'Save error. '.$this->SwfUpload->errorMessage;
			}
		} else {
			$info['message'] = 'empty field name';
		}
		
		if ( strpos($fileinfo['fspath'],'https://') ===false && strpos($fileinfo['fspath'],'http://') ===false  ) {
			$file_url = UPLOAD_FILE_URL.str_replace ( '//', '/', $fileinfo['fspath'] );
		} else {
			$file_url = $fileinfo['fspath'];
		}
		
		if( is_array($fileinfo) && !empty($fileinfo) ){
		    $info = array_merge($fileinfo,$info);
		}
		
		/*$file_url = preg_replace_callback('~(http://img.wx135.com/)([\w|/|\.|_]+)~i',function($matches){
			//print_r($matches);
		    $img_server_nums = 9;
			$sufix = intval(substr(base_convert( md5( $matches[0] ), 16, 10 ),0,6))%$img_server_nums+1;
			$url = 'http://img'.$sufix.'.wx135.com/'.$matches[2];
			return $url;
		},$file_url);*/
		
	   if($_REQUEST['return']=='json'){
	       if($info ['id']) {
	           unset($info['message']);
	           $result = array(
	               'ret' => 0,
	               "msg" => 'success',
	               "data" => $info,
	           );
	       }
	       else{
	           $result = array(
	               'ret' => -1,
	               "msg" => $info ['message'],
	           );
	       }
		   $this->ajaxOutput($result);
		   exit;
		}
		elseif($_REQUEST['return']=='ueditor'){		

		    if($_REQUEST['domain']) {
		        echo "<html><head><script>if(document.domain.indexOf('135editor.com') > 0) {document.domain = '135editor.com';}</script></head><body>";
		    }
		    if($info ['status']){
		        echo json_encode(array(
		            "state" => 'SUCCESS',
		            "url" => $file_url,
		            "title" => $fileinfo['filename'],
		            "media_id" => $fileinfo['media_id'],
		            "original" => $fileinfo['filename'],
		            "type" => $fileinfo['file_type'],
		            "size" => $this->params ['form'] [$file_post_name] ['size']
		        ));
		    }
		    else{
		        echo json_encode(array(
		            "state" => $info['message'],
		            "error" => $info['message']
		        ));
		    }
			
			if($_REQUEST['domain']) {
			    echo "</body></html>";
			}
		}
		elseif($_REQUEST['return']=='ckeditor'){			
			$funcNum = $_REQUEST['CKEditorFuncNum'];			
			if($info ['status']){
				echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "'.($file_url).'", "");</script>';
			}
			else{
				echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "", "'.$info['message'].'");</script>';
			}
		}
		else{
		    if($_REQUEST['return'] == 'xiuxiu') {
		        unset($info['message']);
		    }
		    if( strpos($info['fspath'],'http://') === false && strpos($info['fspath'],'https://') ===false ) {
		        $info['url'] = Router::url($info['fspath'],true);
		    }
		    else{
		        $info['url'] = $info['fspath'];
		    }
		    header('Content-Type: application/json');
			$result = json_encode ( $info );
			echo $result;
		}
		exit ();
	}
}
?>
